package com.wang.cloud.common.sentinel.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.wang.cloud.common.core.api.ApiResult;
import com.wang.cloud.common.core.api.ApiResultCode;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

/**
 * 自定义的-异常处理器
 *
 * @author wang ye
 * @date 2024/7/11
 */
@Slf4j
public class MyBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        ApiResult msg = null;
        // 默认-http状态码
        response.setStatus(ApiResultCode.TOO_MANY_REQUESTS);
        if (e instanceof FlowException) {
            msg = ApiResult.failed(ApiResultCode.TOO_MANY_REQUESTS, "请求限流");
        } else if (e instanceof DegradeException) {
            msg = ApiResult.failed(ApiResultCode.TOO_MANY_REQUESTS, "降级了");
        } else if (e instanceof ParamFlowException) {
            msg = ApiResult.failed(ApiResultCode.TOO_MANY_REQUESTS, "热点参数请求限流");
        } else if (e instanceof SystemBlockException) {
            msg = ApiResult.failed(ApiResultCode.TOO_MANY_REQUESTS, "系统规则（负载/...不满足要求）");
        } else if (e instanceof AuthorityException) {
            response.setStatus(ApiResultCode.HTTP_UNAUTHORIZED);
            msg = ApiResult.failed(ApiResultCode.HTTP_UNAUTHORIZED, "授权规则不通过");
        } else {
            msg = ApiResult.failed(ApiResultCode.TOO_MANY_REQUESTS, "请求限流");
        }
        log.error("BlockException url={} err={}", request.getRequestURI(), msg.getMsg());
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter()
                .write(msg.toString());
    }
}
